package net.p2pcdn.pay;

import net.p2pcdn.core.order.domain.Order;
import net.p2pcdn.core.order.domain.OrderDetail;
import net.p2pcdn.core.order.domain.TradeStatusEnum;
import net.p2pcdn.core.order.service.OrderService;
import net.p2pcdn.core.product.domain.ProductType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class OrderProcessorFactory {
    @Autowired
    private OrderService orderService;
    public Map<ProductType, OrderProcessor> map = new ConcurrentHashMap<>();

    public void addProcessor(ProductType productType, OrderProcessor processor) {
        map.put(productType, processor);
    }

    public void process(String paymentId, String payerId, String orderNo) {
        Order order = orderService.findOrderByTradeNo(orderNo);
        if (order == null) {
            return;
        }
        if (order.getTradeStatus() == TradeStatusEnum.WAIT_BUYER_PAY.getValue()) {
            OrderDetail orderDetail = orderService.getOrderDetail(order.getId());
            ProductType productType = ProductType.get(orderDetail.getItemType());
            map.get(productType).process(order.getBuyer(), orderDetail);
            order.setTradeStatus(TradeStatusEnum.TRADE_SUCCESS.getValue());
            order.setPayTime(new Date());
            order.setPayerId(payerId);
            order.setTransactionId(paymentId);
            orderService.save(order);
        }
    }

    public void cancelOrder(String orderNo){
        orderService.cancelOrder(orderNo);
    }
}
